<template>
  <div ref="codeEditRef">
  </div>
</template>

<script>
import ace from "ace-builds";
import "ace-builds/src-noconflict/ext-language_tools"; // 启动提示菜单
import "ace-builds/src-noconflict/ext-emmet";
// 导入sql
import 'ace-builds/src-noconflict/mode-sql'
import 'ace-builds/src-noconflict/snippets/sql'
// 导入主题
import 'ace-builds/src-noconflict/theme-cloud9_night'
ace.config.set('workerPath','node_modules/ace-builds/src-noconflict') // 设置worker基础路径
ace.require('ace/ext/language_tools') // 这个是自定义补全
ace.require('ace/ext/ext-emmet')
// webpack 按需引入避免打包过大
// ace.config.setModuleUrl('ace/mode/javascript_worker', require('file-loader?esModule=false!ace-builds/src-noconflict/worker-javascript.js'))
// ace.config.setModuleUrl('ace/theme/cloud9_night', require('file-loader?esModule=false!ace-builds/src-noconflict/theme-cloud9_night.js'))
// ace.config.setModuleUrl('ace/ext/language_tools', require('file-loader?esModule=false!ace-builds/src-noconflict/ext-language_tools.js'))
// ace.config.setModuleUrl('ace/ext/emmet', require('file-loader?esModule=false!ace-builds/src-noconflict/ext-emmet.js'))
// ace.config.setModuleUrl('ace/snippets/sql', require('file-loader?esModule=false!ace-builds/src-noconflict/snippets/sql.js'))
// ace.config.setModuleUrl('ace/mode/sql', require('file-loader?esModule=false!ace-builds/src-noconflict/mode-sql.js'))
// 格式化
import {SqlFormatter} from './SqlFormatter'

export default {
  name:"SqlCodeEdit",
  model:{
    event:'update:value',
    prop:'value'
  },
  props:{
    value:{
      type:String,
      default:''
    },
  },
  watch:{
    value(newProps){
      if(this.codeEdit){
        //解决光标移动问题
        const position = this.codeEdit.getCursorPosition();
        this.codeEdit.getSession().setValue(newProps);
        this.codeEdit.clearSelection();
        this.codeEdit.moveCursorToPosition(position);
      }
    },
  },
  data(){
    return{
      codeEdit:null,
    }
  },
  mounted() {
    this.codeEdit = ace.edit(this.$refs.codeEditRef,{
      tabSize: 2,
      maxLines: 25,
      minLines: 25,
      showPrintMargin: false,
      fontSize: 20,
      theme: "ace/theme/cloud9_night", // 设置主题
      mode: "ace/mode/sql", // 设置语言
    })
    this.codeEdit.getSession().setUseWrapMode(true);
    this.codeEdit.on("change",()=>{
      this.$emit('update:value',this.codeEdit.getValue())
    })
    //快捷键
    this.codeEdit.commands.addCommand({
      name: 'formatter',
      bindKey: { win: 'Ctrl-Shift-F', mac: 'Command-Shift-F' },
      exec: () => this.formatterCode()
    })
    this.codeEdit.setValue(this.value);
  },
  methods:{
    formatterCode() {
      this.codeEdit.setValue(SqlFormatter.format(this.value, { language: 'sql', tabWidth: 2, indentStyle:'standard' }))
    }
  },
  beforeDestroy() {
    if(this.codeEdit){
      this.codeEdit.destroy()
    }
  }
}
</script>

<style scoped lang="scss">
.cardHeader{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
